# coding: utf-8
import sys

from PySide6.QtCore import Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QFileDialog, QWidget, QVBoxLayout
from qfluentwidgets import FluentIcon as FIF, PushSettingCard, MessageBoxBase, BodyLabel, LineEdit, CaptionLabel, \
    setFont, MessageBox

from common import cfg, CACHE_DIR, get_folder_size, TaskDao, signalBus, SingleIcon
from threads import speed_to_str, send_sql_request


class UAMessageBox(MessageBoxBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.titleLabel = BodyLabel('请输入 User-Agent', self)
        self.lineEdit = LineEdit(self)
        self.tooltipLabel = CaptionLabel('请输入User-Agent', self)

        setFont(self.titleLabel, 20)
        self.lineEdit.setPlaceholderText('请输入 User-Agent')
        self.lineEdit.setClearButtonEnabled(True)
        self.tooltipLabel.setTextColor(QColor('#f03e3e'), QColor('#f03e3e'))
        self.tooltipLabel.setVisible(False)

        self.viewLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addSpacing(11)
        self.viewLayout.addWidget(self.lineEdit)
        self.viewLayout.addWidget(self.tooltipLabel)
        self.widget.setMinimumSize(500, 200)

    def validate(self) -> bool:
        ua = self.lineEdit.text()
        if not ua:
            self.tooltipLabel.setVisible(True)
            self.lineEdit.setError(True)
            return False
        else:
            self.tooltipLabel.setVisible(False)
            self.lineEdit.setError(False)
            cfg.set(cfg.userAgent, ua)
            return True


class AppSettingWidget(QWidget):
    """ setting widget. """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.downloadCard = PushSettingCard(
            '选择默认下载路径',
            FIF.DOWNLOAD,
            '默认下载路径',
            cfg.get(cfg.downloadFolder),
            parent=self
        )
        self.uaCard = PushSettingCard(
            '修改 User-Agent',
            FIF.PEOPLE,
            'User-Agent',
            cfg.get(cfg.userAgent),
            parent=self
        )
        self.cacheCard = PushSettingCard(
            '清空缓存',
            FIF.BROOM,
            '清空缓存',
            f'缓存大小: {speed_to_str(get_folder_size(CACHE_DIR))}',
            parent=self
        )
        self.ffmpegCard = PushSettingCard(
            '选择 ffmpeg 路径',
            SingleIcon.FFMPEG,
            'FFmpeg 路径',
            cfg.get(cfg.ffmpegPath),
            parent=self
        )

        self.__initWidgets()

    def __initWidgets(self):
        ua = self.uaCard.fontMetrics().elidedText(cfg.get(cfg.userAgent), Qt.TextElideMode.ElideMiddle, 500)
        self.uaCard.setContent(ua)
        # 添加到布局
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.downloadCard)
        self.verticalLayout.addWidget(self.uaCard)
        self.verticalLayout.addWidget(self.cacheCard)
        self.verticalLayout.addWidget(self.ffmpegCard)
        # 事件绑定
        self.downloadCard.clicked.connect(self.onDownloadCardClicked)
        self.uaCard.clicked.connect(self.onUaCardClicked)
        self.cacheCard.clicked.connect(self.onCacheCardClicked)
        self.ffmpegCard.clicked.connect(self.onFfmpegCardClicked)

    def onDownloadCardClicked(self):
        folder = QFileDialog.getExistingDirectory(self, '选择下载路径', cfg.get(cfg.downloadFolder),
                                                  QFileDialog.Option.ShowDirsOnly)
        if folder:
            self.downloadCard.setContent(folder)
            cfg.set(cfg.downloadFolder, folder)

    def onUaCardClicked(self):
        dialog = UAMessageBox(self.window())
        if dialog.exec():
            ua = dialog.lineEdit.text()
            ua = self.uaCard.fontMetrics().elidedText(ua, Qt.TextElideMode.ElideMiddle, 500)
            self.uaCard.setContent(ua)

    def onCacheCardClicked(self):
        dialog = MessageBox(
            '清空缓存',
            '确定要清空缓存吗？\n清空时会清除所有正在进行或已完成的任务，清空后将无法恢复。',
            self.window()
        )
        if dialog.exec():
            send_sql_request(TaskDao.clear)
            signalBus.clearCacheSig.emit()
            for file in CACHE_DIR.glob('**/*'):
                if file.is_file():
                    file.unlink()
            self.cacheCard.setContent(f'缓存大小: {speed_to_str(get_folder_size(CACHE_DIR))}')

    def onFfmpegCardClicked(self):
        if sys.platform == 'win32':
            ft = 'FFmpeg Executable (*.exe)'
        else:
            ft = 'FFmpeg Executable (*)'
        file, _ = QFileDialog.getOpenFileName(self, '选择 ffmpeg 路径', '', ft)
        if file:
            self.ffmpegCard.setContent(file)
            cfg.set(cfg.ffmpegPath, file)
